package com.luckku.boot.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.luckku.boot.common.api.ApiResult;
import com.luckku.boot.model.entity.Goods;
import com.luckku.boot.model.entity.GoodsStore;
import com.luckku.boot.service.IGoodsService;
import com.luckku.boot.service.IGoodsStoreService;
import com.luckku.boot.utils.SnowFlakeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @author luckku
 * @date 2021/12/12
 */

@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    IGoodsService goodsService;
    @Autowired
    IGoodsStoreService goodsStoreService;
    @Autowired
    SnowFlakeUtil snowFlakeUtil;


    /**
     * /goods/changeGoodsNum
     * 出入库
     */
    @ResponseBody
    @PostMapping("/changeGoodsNum")
    public ApiResult<Goods> changeGoodsNum(@RequestParam("goodsId") Long goodsId,
                                           @RequestParam("storeId") Long storeId,
                                           @RequestParam("num") Long num,
                                           @RequestParam("isAdd") boolean isAdd) {
        GoodsStore goods = goodsStoreService.getOne(
                new QueryWrapper<GoodsStore>().eq("goods_id", goodsId)
                        .eq("store_id", storeId)
        );
        if (isAdd) {
            goodsStoreService.update(goods,
                    new UpdateWrapper<GoodsStore>().eq("goods_id", goodsId)
                    .eq("store_id", storeId).set("remain_num",goods.getRemainNum()+num));
        } else {
            long l = goods.getRemainNum() - num;
            if (l<0) {
                return ApiResult.failed("出库数量大于已有库存");
            }
            goodsStoreService.update(goods,
                    new UpdateWrapper<GoodsStore>().eq("goods_id", goodsId)
                    .eq("store_id", storeId).set("remain_num",l));
        }

        return ApiResult.success();
    }

        /**
         * /goods/goodsListPage
         * 以list形式获取所有商品（带分页参数）(goodsStore)
         */
    @ResponseBody
    @GetMapping("/goodsListPage")
    public ApiResult<Page<GoodsStore>> goodsStoreListPage(@RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(value = "size", defaultValue = "10") Integer pageSize,
                                                     @RequestParam("storeId") String storeId) {
        Page<GoodsStore> list = goodsService.getList(new Page<>(pageNo, pageSize), storeId);
        return ApiResult.success(list);
    }

    /**
     * /goods/goodsPage
     * 以list形式获取所有商品（带分页参数）(goods+seckill)
     */
    @ResponseBody
    @GetMapping("/goodsPage")
    public ApiResult<Page<Goods>> goodsPage(@RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(value = "size", defaultValue = "10") Integer pageSize) {
        Page<Goods> list = goodsService.getUnstoreList(new Page<Goods>(pageNo, pageSize));
        return ApiResult.success(list);
    }

    /**
     * /goods/goodsOff
     * 商品下架
     */
    @ResponseBody
    @DeleteMapping("/goodsOff")
    public ApiResult<Goods> goodsOff(@RequestParam("goodsId") Long goodsId,
                                           @RequestParam("storeId") Long storeId) {
        goodsStoreService.remove(
                new QueryWrapper<GoodsStore>().eq("goods_id", goodsId)
                        .eq("store_id", storeId)
        );
        return ApiResult.success();
    }

    /**
     * /goods/goodsOn
     * 商品上架
     */
    @ResponseBody
    @PostMapping("/goodsOn")
    public ApiResult<Goods> goodsOn(@RequestParam("goodsId") String goodsId,
                                    @RequestParam("storeId") String storeId,
                                    @RequestParam("num") Long num) {
        GoodsStore store = goodsStoreService.getOne(
                new QueryWrapper<GoodsStore>().eq("goods_id", goodsId)
                        .eq("store_id", storeId)
        );
        if (store!=null) {
            return ApiResult.failed("该店铺已存在该商品");
        }
        Goods goods = goodsService.getSeckillGoods(goodsId);
        GoodsStore goodsStore = GoodsStore.builder().goodsId(goods.getGoodsId()).img(goods.getImg())
                .realPrice(goods.getRealPrice()).price(goods.getPrice())
                .title(goods.getTitle()).description(goods.getDescription())
                .storeId(storeId).remainNum(num).build();
        goodsStoreService.save(goodsStore);
        return ApiResult.success();
    }

    /**
     * /goods/addGoods
     * 根据信息添加商品
     */
    @ResponseBody
    @PostMapping("/addGoods")
    public ApiResult<Goods> addGoods(@RequestBody Goods dto) {

        Goods goods = Goods.builder()
                .goodsId(String.valueOf(snowFlakeUtil.snowflakeId()))
                .title(dto.getTitle())
                .description(dto.getDescription())
                .price(dto.getPrice())
                .img(dto.getImg())
                .build();
        goodsService.save(goods);
        return ApiResult.success(goods);
    }


    /**
     * /goods/all
     * 获取所有商品
     */
    @ResponseBody
    @GetMapping("/all")
    public ApiResult<List<Goods>> getAllGoods() {
        List<Goods> list = goodsService.list();
        return ApiResult.success(list);
    }

    /**
     * /goods/list
     * 获取所有商品（按照前端数据要求的两层封装格式）
     */
    @ResponseBody
    @GetMapping("/list")
    public ApiResult<List<List<Goods>>> getListGoods() {
        List<Goods> list1 = goodsService.getGoodsList(true);
        List<Goods> list2 = goodsService.getGoodsList(false);
        List<List<Goods>> list = new ArrayList<>();
        list.add(list1);
        list.add(list2);
        return ApiResult.success(list);
    }

    /**
     * /goods/getById?goodsId=1
     * 根据id获取商品
     */
    @ResponseBody
    @GetMapping("/getById")
    public ApiResult<Goods> getGoodsById(@RequestParam("goodsId") Long goodsId) {
        return ApiResult.success(goodsService.getById(goodsId));
    }

    /**
     * /goods/getByName?name=子
     * 根据名称获取商品
     */
    @ResponseBody
    @GetMapping("/getByName")
    public ApiResult<List<Goods>> getGoodsByName(@RequestParam("title") String title) {
        return ApiResult.success(goodsService.getByStrLike("title", title));
    }

    /**
     * /goods/getGoodsByAll?goodsId=1&&goodsName=纸&&supplierId=2
     * 根据三个条件模糊查询商品
     */
    @ResponseBody
    @GetMapping("/getGoodsByAll")
    public ApiResult<List<Map<String, Object>>> getGoodsByAll(
            @RequestParam(defaultValue = "") String goodsId,
            @RequestParam(defaultValue = "") String title,
            @RequestParam(defaultValue = "") String price
    ) {
        List<Map<String, Object>> goods = goodsService.listMaps(
                new LambdaQueryWrapper<Goods>()
                        .like(Goods::getGoodsId, goodsId)
                        .like(Goods::getTitle, title)
                        .like(Goods::getPrice, price));
        return ApiResult.success(goods);
    }


    /**
     * /goods/saveOne
     * 使用小驼峰传参 如：goodsTypeId
     * 新建一个商品
     */
    @ResponseBody
    @PostMapping("/saveOne")
    public ApiResult<Goods> saveOne(Goods goods) {
        goodsService.save(goods);
        return ApiResult.success(goods);
    }

    /**
     * /goods/saveBatch
     * 新建一组商品
     */
    @ResponseBody
    @PostMapping("/saveBatch")
    public ApiResult<List<Goods>> saveBatch(List<Goods> goodsList) {
        goodsService.saveBatch(goodsList);
        return ApiResult.success(goodsList);
    }


    /**
     * /goods/updateById
     * 使用小驼峰传参 如：goodsTypeId
     * 更新一个商品
     */
    @ResponseBody
    @PutMapping("/updateById")
    public ApiResult<Goods> updateById(Goods goods) {
        goodsService.updateById(goods);
        return ApiResult.success(goods);
    }

    /**
     * /goods/updateBatchById
     * 更新一组商品
     */
    @ResponseBody
    @PutMapping("/updateBatchById")
    public ApiResult<List<Goods>> updateBatchById(List<Goods> goodsList) {
        goodsService.updateBatchById(goodsList);
        return ApiResult.success(goodsList);
    }

    /**
     * /goods/removeById
     * 根据id移除一个商品
     */
    @ResponseBody
    @DeleteMapping("/removeById")
    public ApiResult<Long> removeById(Long goodsId) {
        goodsService.removeById(goodsId);
        return ApiResult.success(goodsId);
    }

    /**
     * /goods/removeByIds
     * 根据id组移除一组商品
     */
    @ResponseBody
    @DeleteMapping("/removeByIds")
    public ApiResult<Collection<Long>> removeByIds(Collection<Long> goodsIdList) {
        goodsService.removeByIds(goodsIdList);
        return ApiResult.success(goodsIdList);
    }


}
